package run;

import java.awt.Rectangle;

import hypermedia.video.Blob;
import hypermedia.video.OpenCV;
import processing.core.PApplet;
import processing.core.PImage;

public class CVSuperImposition {

	public static int contrast_lev = 20;
	public static int bright_lev = 80;

	private OpenCV opencv;
	private PApplet p;

	private boolean capture_mode = false;
	private boolean display_thresh = true;
	private PImage thresholded_img;
	private PImage unthresholded_img;
	
	public CVSuperImposition(OpenCV opencv, PApplet applet) {
		this.opencv = opencv;
		this.p = applet;
	}

	synchronized public Blob[] analyze() {
		this.unthresholded_img = opencv.image();
		opencv.convert(p.GRAY);
	    
	    opencv.contrast(contrast_lev);
	    opencv.brightness(bright_lev);
	    
	  	opencv.threshold(5, 255, OpenCV.THRESH_OTSU );    // set black & white threshold 
//	    if (display_thresh) {
//	    	p.image(opencv.image(),0,0); //TODO danger; crashasble.
//	    }
	    this.thresholded_img = opencv.image();

//	    image(opencv.image(), 0, 0);
	    Blob[] blobs = opencv.blobs( 100, p.width*p.height/2,
	    		100, true, OpenCV.MAX_VERTICES*4 );

	    // draw blob results
	    System.out.println(blobs.length);
	    //TODO let this be only analysis, push list of objs
	    // back for main drawing loop to render
	    
//	    for( int i=0; i<blobs.length; i++ ) {
//		    p.fill(50);
//	        p.beginShape();
//	        for( int j=0; j<blobs[i].points.length; j++ ) {
//	        	
//	            int blobx = blobs[i].points[j].x;
//				int bloby = blobs[i].points[j].y;
//				p.vertex( blobx, bloby );
//	        }
//	        p.endShape(p.CLOSE);
//	        
//	        p.stroke(0,60,0);
//	        p.fill(70,0,0,70);
//	    	Rectangle rect = blobs[i].rectangle;
//	    	p.rect(rect.x, rect.y, rect.width, rect.height);
//	    	
//	    }
	    
	    return blobs;
	}
	
	public PImage getThresholdedImage() {
		return thresholded_img;
	}
	
	public PImage getUnthresholdedImage() {
		return unthresholded_img;
	}
}
